﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using STKMIS.BLL;
using STKMIS.Model;

namespace STKMIS
{
    public partial class FrmPurchaseInStorage : FrmBase
    {
        private static Dictionary<int,List<ProductsAndUnitModel>> productAndUnitDic=new Dictionary<int,List<ProductsAndUnitModel>>();
        public FrmPurchaseInStorage()
        {
            InitializeComponent();
        }

        private void FrmPurchaseInStorage_Load(object sender, EventArgs e)
        {
            DataTable dtSupplier = ProductSupplier.GetProductSupplierListByType("",0);
            if (dtSupplier != null && dtSupplier.Rows.Count > 0)
            {
                List<ComboxGridViewColumns> gvColumnList = new List<ComboxGridViewColumns>
             {
                 new ComboxGridViewColumns("Name","供货商名称",150),
                 new ComboxGridViewColumns("LinkMan","联系人",100),
                 new ComboxGridViewColumns("Telphone","手机",120),
                 new ComboxGridViewColumns("Address","地址",150),
                 new ComboxGridViewColumns("Id","ID",false)
             };

                this.mcComboxProvider.GrvColumnsList = gvColumnList;
                this.mcComboxProvider.KeyWordsColumn = "Name,LinkMan,Telphone,Address";
                this.mcComboxProvider.DisplayMemberColumn = "Name";
                this.mcComboxProvider.ValueMemberColumn = "Id";
                this.mcComboxProvider.PopupGridAutoSize = false;
                this.mcComboxProvider.IsShowEvent = false;
                this.mcComboxProvider.DropDownHeight = 300;
                this.mcComboxProvider.DropDownWidth = 240;
                this.mcComboxProvider.DataSource = dtSupplier;
                this.mcComboxProvider.RowFilterVisible = true;
            }
            else
            {
                this.mcComboxProvider.Enabled = false;
            }

            DataTable dtProduct = Product.GetProductList("");
            if (dtProduct != null && dtProduct.Rows.Count > 0)
            {
                //初始化列表产品下拉列表
                List<ComboxGridViewColumns> gvProductColumnList = new List<ComboxGridViewColumns>
             {
                  new ComboxGridViewColumns("ProductCode","产品编码"),
                 new ComboxGridViewColumns("ProductName","产品名称",250),
                 new ComboxGridViewColumns("ProductNamePY","产品名称拼音",false),
                 new ComboxGridViewColumns("ProductStandard","标准(型号)"),
                 new ComboxGridViewColumns("ProTypeName","类型"),
                  new ComboxGridViewColumns("ProductID","ID",false)
             };

                this.ProductName.GrvColumnsList = gvProductColumnList;
                this.ProductName.IsShowEvent = true;
                this.ProductName.KeyWordsColumn = "ProductName,ProductNamePY,ProductCode,ProTypeName";
                this.ProductName.DisplayMemberColumn = "ProductName";
                this.ProductName.ValueMemberColumn = "ProductID";
                this.ProductName.dataSource = dtProduct;

                DataTable dtUnit = STKMIS.BLL.ProductUnit.GetProductUnitList("");
                this.Unit.DataSource = dtUnit;
                this.Unit.DisplayMember = "ProUnitName";
                this.Unit.ValueMember = "ProUnitID";

            }
            else
            {
                this.dgvPurchaseItem.Enabled = false;
            }
        }

        private void dgvPurchaseItem_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (e.Control is MultiColumnsCombox)
            {
                (e.Control as MultiColumnsCombox).DoubleClickItemHandler -= new CellsDoubleClickHandler(mcComboxProduct_DoubleClickItemHandler);
                (e.Control as MultiColumnsCombox).DoubleClickItemHandler += new CellsDoubleClickHandler(mcComboxProduct_DoubleClickItemHandler);
            }
            //判断要处理的DataGridViewComboBoxColumn名称，若符合条件，编辑控件被强制转换为TextBox以处理，添加SelectedIndexChanged事件
            if (this.dgvPurchaseItem.CurrentCell.OwningColumn.Name == "PurchaseAmount")
            {
                ((TextBox)e.Control).TextChanged -= new EventHandler(txtPurchaseAmount_TextChanged);
                ((TextBox)e.Control).TextChanged += new EventHandler(txtPurchaseAmount_TextChanged);

                ((TextBox)e.Control).KeyPress -= new KeyPressEventHandler(txtValid_KeyPress);
                ((TextBox)e.Control).KeyPress += new KeyPressEventHandler(txtValid_KeyPress);
            }
            if (this.dgvPurchaseItem.CurrentCell.OwningColumn.Name == "PurchasePrice")
            {
                ((TextBox)e.Control).TextChanged -= new EventHandler(txtPurchasePrice_TextChanged);
                ((TextBox)e.Control).TextChanged += new EventHandler(txtPurchasePrice_TextChanged);

                ((TextBox)e.Control).KeyPress -= new KeyPressEventHandler(txtValid_KeyPress);
                ((TextBox)e.Control).KeyPress += new KeyPressEventHandler(txtValid_KeyPress);
            }

            if (this.dgvPurchaseItem.CurrentCell.OwningColumn.Name == "Unit")
            {
                ((ComboBox)e.Control).SelectedIndexChanged -= new EventHandler(comboxUnit_SelectedIndexChanged);
                ((ComboBox)e.Control).SelectedIndexChanged += new EventHandler(comboxUnit_SelectedIndexChanged);
            }
        }

        private void mcComboxProduct_DoubleClickItemHandler(object sender, DoubleClickEventArgs e)
        {
            DataGridViewRow row = e.Value as DataGridViewRow;
            this.dgvPurchaseItem[0, e.RowIndex].Value = row.Cells["ProductName"].Value.ToString();
            this.dgvPurchaseItem[1, e.RowIndex].Value = row.Cells["ProductStandard"].Value.ToString();
            
            this.dgvPurchaseItem[9, e.RowIndex].Value = row.Cells["ProductID"].Value.ToString();
            
        }

        private void txtPurchaseAmount_TextChanged(object sender, EventArgs e)
        {
            TextBox txtPurchaseAmount = sender as TextBox;
            int rowIndex = ((DataGridViewTextBoxEditingControl)(sender)).EditingControlRowIndex;
            decimal purchasePrice = 0m;
            if (dgvPurchaseItem[4, rowIndex].Value == null || dgvPurchaseItem[4, rowIndex].Value.ToString() == "")
            {
                purchasePrice = 0m;
            }
            else
            {
                purchasePrice = dgvPurchaseItem[4, rowIndex].Value.ToString() == "" ? 0m : Convert.ToDecimal(dgvPurchaseItem[4, rowIndex].Value.ToString().Trim());
            }

            if (txtPurchaseAmount.Text.Trim() == "" || txtPurchaseAmount.Text.Trim() == ".")
            {
                txtPurchaseAmount.Text = "0";
            }
            this.dgvPurchaseItem[5, rowIndex].Value = (purchasePrice * Convert.ToDecimal(txtPurchaseAmount.Text.Trim())).ToString();
            PurchaseSumMoney();
        }

        private void txtPurchasePrice_TextChanged(object sender, EventArgs e)
        {
            TextBox txtPurchasePrice = sender as TextBox;
            int rowIndex = ((DataGridViewTextBoxEditingControl)(sender)).EditingControlRowIndex;
            decimal purchaseAmount = 0m;
            if (dgvPurchaseItem[3, rowIndex].Value == null || dgvPurchaseItem[3, rowIndex].Value.ToString() == "")
            {
                purchaseAmount = 0m;
            }
            else
            {
                purchaseAmount = dgvPurchaseItem[3, rowIndex].Value.ToString() == "" ? 0m : Convert.ToDecimal(dgvPurchaseItem[3, rowIndex].Value.ToString().Trim());
            }

            if (txtPurchasePrice.Text.Trim() == "" || txtPurchasePrice.Text.Trim() == ".")
            {
                txtPurchasePrice.Text = "0";
            }
            this.dgvPurchaseItem[5, rowIndex].Value = (purchaseAmount * Convert.ToDecimal(txtPurchasePrice.Text.Trim())).ToString();
            PurchaseSumMoney();
        }

        private void PurchaseSumMoney()
        {
            decimal sumMoney = 0m;
            foreach (DataGridViewRow dgvr in dgvPurchaseItem.Rows)
            {
                if (dgvr.Cells[5].Value != null)
                {
                    decimal rowsum = dgvr.Cells[5].Value.ToString() == "" ? 0m : Convert.ToDecimal(dgvr.Cells[5].Value.ToString());
                    sumMoney = sumMoney + rowsum;
                }
            }
            txtPurchaseSumMoney.Text = sumMoney.ToString();
        }

        private void txtValid_KeyPress(object sender, KeyPressEventArgs e)
        {
            TextBox txtStr = sender as TextBox;

            //检测是否已经输入了小数点
            bool IsContainsDot = txtStr.Text.Contains(".");
            if ((e.KeyChar < 48 || e.KeyChar > 57) && (e.KeyChar != 8) && (e.KeyChar != 46))
            {
                e.Handled = true;
            }
            else if (IsContainsDot && (e.KeyChar == 46)) //如果输入了小数点，并且再次输入
            {
                e.Handled = true;
            }
        }
        private void comboxUnit_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox comboxUnit = sender as ComboBox;
            int rowIndex = ((DataGridViewComboBoxEditingControl)(sender)).EditingControlRowIndex;
            this.dgvPurchaseItem[10, rowIndex].Value = comboxUnit.SelectedValue.ToString();
            this.dgvPurchaseItem[6, rowIndex].Value = comboxUnit.Text.ToString();
        }

        private void dgvPurchaseItem_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                try
                {
                    if (dgvPurchaseItem.Columns[e.ColumnIndex].Name.ToUpper() == "DELETEPRODUCT")
                    {
                        if (DialogResult.OK == MessageBox.Show("确认要删除该行数据吗？", "删除确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                        {
                            dgvPurchaseItem.Rows.RemoveAt(e.RowIndex);
                            if (productAndUnitDic.ContainsKey(e.RowIndex))
                            {
                                productAndUnitDic.Remove(e.RowIndex);
                            }
                            PurchaseSumMoney();
                        }
                    }
                    if (dgvPurchaseItem.Columns[e.ColumnIndex].Name.ToUpper() == "SETSALEUNIT")
                    {
                        //选择了单位才能点击设置
                        decimal purchaseAmount=0m;
                        decimal purchasePrice = 0m;
                        int unitID = 0;
                        string unitName="";
                        //if (this.dgvPurchaseItem[3, e.RowIndex].Value != null && this.dgvPurchaseItem[3, e.RowIndex].Value.ToString() != "")
                        //{
                        //    purchaseAmount = Convert.ToDecimal(this.dgvPurchaseItem[3, e.RowIndex].Value.ToString().Trim());
                        //}
                        //else
                        //{
                        //    MessageBox.Show("请先填写采购数量。", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        //    return;
                        //}
                        //if (this.dgvPurchaseItem[4, e.RowIndex].Value != null && this.dgvPurchaseItem[4, e.RowIndex].Value.ToString() != "")
                        //{
                        //    purchasePrice =  Convert.ToDecimal(this.dgvPurchaseItem[4, e.RowIndex].Value.ToString().Trim());
                        //}
                        //else
                        //{
                        //    MessageBox.Show("请先填写采购单价。", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        //    return;
                        //}
                        if (this.dgvPurchaseItem[9, e.RowIndex].Value == null || this.dgvPurchaseItem[9, e.RowIndex].Value.ToString() == "")
                        {
                            MessageBox.Show("请先选择采购产品。", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }
                        
                        if (this.dgvPurchaseItem[10, e.RowIndex].Value != null && this.dgvPurchaseItem[10, e.RowIndex].Value.ToString() != "")
                        {
                            unitID = Convert.ToInt32(this.dgvPurchaseItem[10, e.RowIndex].Value.ToString().Trim());
                            unitName = this.dgvPurchaseItem[2, e.RowIndex].FormattedValue.ToString();
                        }
                        else
                        {
                            MessageBox.Show("请先填写产品单位。", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }
                        if (unitID != 0)
                        {
                            FrmPurchaseSetSaleUnit frmChidle = new FrmPurchaseSetSaleUnit();
                            frmChidle.unitID = unitID;
                            frmChidle.purchaseAmout = purchaseAmount;
                            frmChidle.purchasePrice = purchasePrice;
                            frmChidle.unitName = unitName;
                            if (productAndUnitDic.ContainsKey(e.RowIndex))
                            {
                                frmChidle.productsAndUnitInfoList = productAndUnitDic[e.RowIndex];
                            }
                            this.DialogResult = frmChidle.ShowDialog(this);
                            if (this.DialogResult == DialogResult.Yes)
                            {
                                if (productAndUnitDic.ContainsKey(e.RowIndex))
                                {
                                    //更新该键的值
                                    productAndUnitDic[e.RowIndex] = frmChidle.productsAndUnitInfoList;
                                }
                                else
                                {
                                    //插入该键的值
                                    productAndUnitDic.Add(e.RowIndex, frmChidle.productsAndUnitInfoList);
                                   
                                }
                                ViewSaleUnit(e.RowIndex,frmChidle.productsAndUnitInfoList);
                            }
                        }
                    }
                }
                catch
                {

                }
            }
        }

        private void ViewSaleUnit(int rowIndex,List<ProductsAndUnitModel> productsAndUnitInfoList)
        {
            //this.dgvPurchaseItem[6, rowIndex].Value=
        }

        private void btnSave_Click(object sender, EventArgs e)
        {

        }
    }
}
